package com.tang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.reggie.exception.CustomException;
import com.tang.reggie.mapper.CategoryMapper;
import com.tang.reggie.mapper.DishMapper;
import com.tang.reggie.mapper.SetmealMapper;
import com.tang.reggie.pojo.Category;
import com.tang.reggie.pojo.Dish;
import com.tang.reggie.pojo.Setmeal;
import com.tang.reggie.service.CategoryService;
import com.tang.reggie.service.DishService;
import com.tang.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired
    private DishService dishService;
    
    @Autowired
    private SetmealService setmealService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Category> findPage(int page,int pageSize) {
        //分页条件
        IPage<Category> iPage = new Page<>(page, pageSize);
        //排序条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);

        //查询
        //因为调用的是父类的page方法，所以这里用super会明确调用的具体方法，可读性好 且不会被自身的重写后的方法影响
        super.page(iPage, categoryLambdaQueryWrapper);
        return iPage;
    }

    /**
     * 分类删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        //根据id查询在菜品表中是否存在该id
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        if (count1>0){
            //在菜品中存在,抛出异常提示//抛出给调用者
            throw new CustomException("菜品中存在该分类，不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2>0){
            //在套餐中存在
            throw new CustomException("套餐中存在该分类，不能删除");
        }

        //正常删除
        super.removeById(id);
    }
}
